import 'dart:convert';

import 'package:city_pickers/city_pickers.dart';
import 'package:common_utils/common_utils.dart';
import 'package:fluro/fluro.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';
import 'package:image_picker/image_picker.dart';

import '../config/config.dart';
import '../entity/user_info_entity.dart';
import '../http/api.dart';
import '../provider/userinfo_provider.dart';
import '../routers/routers.dart';

class MineInfo extends StatefulWidget {
  const MineInfo({Key? key}) : super(key: key);

  @override
  State<MineInfo> createState() => _MineInfoState();
}

class _MineInfoState extends State<MineInfo> {
  // late UserInfoEntity infoEntity;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
  }

  chooseImage() async {
    final ImagePicker _picker = ImagePicker();
    final XFile? image = await _picker.pickImage(source: ImageSource.gallery);
    String? imgPah = image?.path;
    if (imgPah != null) {
      var result = await Api.upLoadImg(imgPah);
      var jsonResult = jsonDecode(jsonEncode(result));
      // LogUtil.v(jsonResult['url']);
      upUserinfo2(jsonResult['url']);
    }
  }

  ///
  /// 更新个人信息
  ///
  upUserinfo2(String headImg) async {
    // UserInfoEntity infoEntity =
    //     Provider.of<UserInfoProvider>(context, listen: false).userInfo;
    // infoEntity.user.headicon = headImg;
    //
    // Map a = {'userinfo': Map.from(infoEntity.user.toJson())};
    // dynamic result = await Api.changeUserinfo(a);
    //
    // var jsonResult = jsonDecode(jsonEncode(result));
    // if (jsonResult['code'] == 200) {
    //   EasyLoading.showToast("修改成功");
    //   Provider.of<UserInfoProvider>(context, listen: false)
    //       .changeUserinfo(infoEntity);
    // }
  }

  ///
  /// 弹出省市区三级选择器
  ///
  getCityResult() async {
    // type 1
    Result? result = await CityPickers.showCityPicker(
      context: context,
      height: 600.w,
      barrierOpacity: 0.5,
      theme: Theme.of(context).copyWith(),
    );
    if (result != null) {
      String str =
          '${result.provinceName}-${result.cityName}-${result.areaName}';
      setState(() {
        // infoEntity.user.address = str;
        // upUserinfo();
      });
    }
  }

  ///
  /// 更新个人信息
  ///
  upUserinfo() async {
    // Map a = {'userinfo': Map.from(infoEntity.user.toJson())};
    // dynamic result = await Api.changeUserinfo(a);
    // var jsonResult = jsonDecode(jsonEncode(result));
    // if (jsonResult['code'] == 200) {
    //   EasyLoading.showToast("提交成功");
    // }
  }

  ///
  /// 返回普通的列表item
  ///
  Widget getListItem(
      IconData icon, String title, String subTitle, Function() onTap) {
    return ListTile(
      onTap: onTap,
      leading: Icon(icon, size: 43.w),
      title: Text(title, style: TextStyle(fontSize: 25.w)),
      horizontalTitleGap: 0,
      dense: true,
      iconColor: Config.colorText1,
      textColor: Config.colorText1,
      trailing: SizedBox(
        width: 360.w,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Text(subTitle,
                style: TextStyle(fontSize: 23.w, color: Config.colorText3)),
            Padding(padding: EdgeInsets.all(10.w)),
            Icon(Icons.arrow_forward_ios, size: 20.w),
          ],
        ),
      ),
      contentPadding: EdgeInsets.symmetric(vertical: 9.w, horizontal: 0),
    );
  }

  ///
  /// 返回头像item
  ///
  Widget getListItemAvatar(
      IconData icon, String title, String subTitle, Function() onTap) {
    return ListTile(
      onTap: onTap,
      leading: Icon(icon, size: 43.w),
      title: Text(title, style: TextStyle(fontSize: 25.w)),
      horizontalTitleGap: 0,
      dense: true,
      iconColor: Config.colorText1,
      textColor: Config.colorText1,
      trailing: SizedBox(
        width: 300.w,
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Container(
                width: 95.w,
                height: 95.w,
                color: Colors.transparent,
                padding: EdgeInsets.all(3.w),
                child: CircleAvatar(
                  backgroundImage: getHeadImage(subTitle),
                )),
            Padding(padding: EdgeInsets.all(10.w)),
            Icon(Icons.arrow_forward_ios, size: 20.w),
          ],
        ),
      ),
      contentPadding: EdgeInsets.symmetric(vertical: 9.w, horizontal: 0),
    );
  }

  ///
  /// 判断头像有木有，没有就用本地的占位
  ///
  ImageProvider getHeadImage(String url) {
    // if (infoEntity.code == 200 && infoEntity.user.headicon.length > 1) {
    //   return NetworkImage(url);
    // } else {
    return const AssetImage('assets/images/launcher.png');
    // }
  }

  @override
  Widget build(BuildContext context) {
    // infoEntity = Provider.of<UserInfoProvider>(context).userInfo;

    return Scaffold(
      backgroundColor: Config.colorBg2,
      appBar: AppBar(
        title: const Text('个人中心'),
        centerTitle: true,
      ),
      body: Container(
        //中间列表区
        width: double.infinity,
        height: 482.w,
        padding: EdgeInsets.symmetric(vertical: 0, horizontal: 0.w),
        margin: EdgeInsets.symmetric(vertical: 30.w, horizontal: 30.w),
        decoration: BoxDecoration(
          color: (Config.colorWhite),
          borderRadius: BorderRadius.circular(12.w),
        ),
        child: ListView(
          physics: const NeverScrollableScrollPhysics(),
          padding: EdgeInsets.symmetric(vertical: 6.w, horizontal: 30.w),
          children: [
            //${Config.baseUrl}${infoEntity.user.headicon}
            getListItemAvatar(Icons.person, "头像", '', () {
              chooseImage();
            }),
            const Divider(
              height: 0.5,
              color: Config.colorDivider,
            ),
            //infoEntity.user.username
            getListItem(Icons.account_circle_outlined, "账号", "", () {}),
            const Divider(
              height: 0.5,
              color: Config.colorDivider,
            ),
            //infoEntity.user.nickname
            getListItem(Icons.person_add, "昵称", '', () {
              Routes.navigateTo(context, Routes.mineChangeNickname);
            }),
            const Divider(
              height: 0.5,
              color: Config.colorDivider,
            ),
            //infoEntity.user.address
            getListItem(Icons.add_location_alt, "收货地址", '', () {
              Routes.navigateTo(context, Routes.mineAddressManager);
            }),
          ],
        ),
      ),
    );
  }
}
